package in.abacritt.android.xclock;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.content.Context;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.util.Log;

public class XClockLocationClient {

	Context appContext;
	Location currentLocation;
	LocationInfoWrapper locationInfoWrapper;
	Address currentAddress;

	public XClockLocationClient(Context context) {
		this.appContext = context;
		locationInfoWrapper = new LocationInfoWrapper();
	}

	public LocationInfoWrapper getCurrentLocation() {
		LocationManager locManager = (LocationManager) appContext
				.getSystemService(Context.LOCATION_SERVICE);

		String provider = locManager.getBestProvider(new Criteria(), true);

		currentLocation = locManager.getLastKnownLocation(provider);
		locationInfoWrapper.locationAndroid = currentLocation;

		List<String> providerList = locManager.getAllProviders();
		if (null != currentLocation && null != providerList
				&& providerList.size() > 0) {
			double longitude = currentLocation.getLongitude();
			double latitude = currentLocation.getLatitude();
			Geocoder geocoder = new Geocoder(
					appContext.getApplicationContext(), Locale.getDefault());
			try {
				List<Address> listAddresses = geocoder.getFromLocation(
						latitude, longitude, 1);
				if (null != listAddresses && listAddresses.size() > 0) {
					locationInfoWrapper.locationAddress = listAddresses.get(0);
					String currentLocationName = listAddresses.get(0)
							.getLocality();
					Log.d("locationname", currentLocationName);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}

		}

		return locationInfoWrapper;
	}

}
